import { createRouter, createWebHashHistory } from 'vue-router'
import LoginView from '../views/LoginView'
import HomeView from '../views/HomeView'
const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/',
    name: 'home',
    component: HomeView,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        name: 'welcome',
        component: () => import('../views/WelcomeView.vue')
      },
      {
        path: '/user_list',
        name: 'user_list',
        component: () => import('../views/UserView.vue')
      },
      {
        path: '/role_list',
        name: 'role_list',
        component: () => import('../views/MenuView.vue')
      },
      {
        path:'/author_list',
        name:'author_list',
        component:()=>import('../views/AuthorView.vue')
      },
      {
        path:'/group_list',
        name:'group_list',
        component:()=>import('../views/GroupView.vue')
      },
      {
        path:'/attribute_list',
        name:'attribute_list',
        component:()=>import('../views/AttributeView.vue')
      },
      {
        path:'/product_list',
        name:'product_list',
        component:()=>import('../views/ProductView.vue')
      },
      {
        path:'/add_product',
        name:'add_product',
        component:()=>import('../views/AddProduct.vue')
      },
      {
        path:'/order_list',
        name:'order_list',
        component:()=>import('../views/OrderView.vue')
      },
    ]
  }
]
// shop-vue\src\views\WelcomeView.vue
const router = createRouter({
  history: createWebHashHistory(),
  routes
})

export default router

// 验证
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next() // 必须要调用 next() 继续执行后续路由跳转，否则会被阻止
  } else {
    const token = sessionStorage.getItem('token')
    if (!token) {
      next('/login') // 重定向到登录页
    } else {
      next() // 继续后续路由跳转
    }
  }
})